import { ProForm } from "@/components/ProForm";
import { PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import { http } from "@/utils/request";
import {
  Button,
  DatePicker,
  Divider,
  Form,
  Input, message,
  Modal, Radio,
  Row,
  Table,
  Pagination,
  type TableColumnsType
} from "antd";
import dayjs from 'dayjs';
import { useState,useEffect } from "react";

type TableDataType = {
  positionCode: string;
  position: string;
  selfScoringVisibility: string;
  positionSource: string;
  createdBy: string;
  createdTime: string;
}

const PostMaintenance = () => {
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [id,setId] = useState(null);
  const [list, setList] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});

  const columns: TableColumnsType<TableDataType> = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "岗位编号",
      dataIndex: "positionCode"
    },
    {
      align: "center",
      title: "岗位名称",
      dataIndex: "position"
    },
    {
      align: "center",
      title: "自评分是否可见",
      render: (_, record) => {
        return (
          <>
            {record.selfScoringVisibility === "0" && <span>否</span>}
            {record.selfScoringVisibility === "1" && <span>是</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "岗位来源",
      dataIndex: "positionSource"
    },
    {
      align: "center",
      title: "创建人",
      dataIndex: "createdBy"
    },
    {
      align: "center",
      title: "创建时间",
      dataIndex: "createdTime",
      render: (_, record) => {
        return (
          <>
            <span>{dayjs(record.createdTime).format('YYYY-MM-DD')}</span>
          </>
        )
      }
    },
    {
      align: "center",
      title: "操作",
      render: (_, record, index) => {
        return (
          <>
            <Button type={'link'} onClick={() => {
              setCurrentEdit(record);
              setId(record.id);
              editForm.setFieldsValue(record)
              setOpen(true);
            }}>编辑</Button>
            <Button type={'link'} danger onClick={() => {
              Modal.confirm({
                title: "提示",
                content: "此操作将永久删除该部门绩效评价，是否继续？",
                onOk(close){
                  delData(record.id)
                  close();
                }
              })
            }}>删除</Button>
          </>
        )
      }
    }
  ]

  //删除
  const delData = async(id:number) =>{
    try {
      const res = await http.get({
        url:'/PmPosition/removePostion',
        params:{
          postionId:id,
        }
      })
      if(res.code==200){
        message.success('删除成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  const handleOk = async() => {
    try {
      const values = await editForm.validateFields();
      // 校验成功，执行保存操作并关闭Modal
      if(JSON.stringify(currentEdit) === "{}"){
        addSave(values);
      }else{
        editSave(values);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  const handleCancel = () => {
    setOpen(false);
  }
  
  //新增接口
  const addSave = async(data:object) =>{
    try {
      const res = await http.post({
        url:'/PmPosition/savePosition',
        data:data,
      })
      if(res.code==200){
        setOpen(false);
        message.success('岗位新增成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(data:object) =>{
    try {
      const res = await http.post({
        url:'/PmPosition/updatePosition',
        data:{postionId:id,...data}
      })
      if(res.code==200){
        setOpen(false);
        message.success('岗位修改成功!');
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmPosition/positionList',
        params:{
          position:form.getFieldValue().position,
          pageNum:pageNum,
          pageSize:pageSize,
        }
      })
      setList(res.rows);
      setTotal(res.total);
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'} onSearch={() => getList()}>
        <Form.Item
          label={'岗位名称'}
          name="position"
        >
          <Input placeholder="请输入岗位名称" />
        </Form.Item>
      </ProForm>

      <Row className={'mb-[20px]'}>
        <Button type={'primary'} icon={<PlusOutlined />} onClick={() => {
          setOpen(true)
          setId(null)
        }}>新增</Button>
      </Row>

      <Table
        dataSource={list}
        columns={columns}
        bordered
        pagination={false}
        rowKey={(record) => `${record.id}`}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        align="end"
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />
      {/*新增/编辑岗位信息弹窗 */}
      <Modal
        open={open}
        title={`${JSON.stringify(currentEdit) === "{}" ? "新增" : "编辑"}岗位信息`}
        afterClose={() => editForm.resetFields()}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={editForm} initialValues={currentEdit} labelCol={{span: 7}} autoComplete="off">
          <Form.Item
            label={'岗位名称'}
            name={'position'} 
            rules={[{ required: true, message: '请输入岗位名称!' }]}
          >
            <Input placeholder={"请输入岗位名称"}></Input>
          </Form.Item>
          <Form.Item
            label={'是否参与绩效考核'}
            name={'selfScoringVisibility'}
            rules={[{ required: true, message: '请选择是否参与绩效考核!' }]}
          >
            <Radio.Group>
              <Radio value={'1'}>是</Radio>
              <Radio value={'0'}>否</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export default PostMaintenance;
